package com.share.finance.risk.rules.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.share.common.common.Page;
import com.share.common.common.Result;
import com.share.common.utils.HttpUtil;
import com.share.finance.risk.rules.constants.SysConstant;
import com.share.finance.risk.rules.mapper.ProjectMapper;
import com.share.finance.risk.rules.model.db.Project;
import com.share.finance.risk.rules.model.db.ProjectHist;
import com.share.finance.risk.rules.model.vo.ProjectPageReq;
import com.share.finance.risk.rules.model.vo.VariateVo;
import com.share.finance.risk.rules.service.IProjectHistService;
import com.share.finance.risk.rules.service.IProjectService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 工程表  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-11-24
 */
@Slf4j
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {
    private Map<String, Project> map = new HashMap();

    @Value("${rootUrl.core}")
    private String coreRootUrl;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private IProjectHistService projectConfService;

    /**
     * 初始化工程配置----这个由加载kie容器,他来执行初始化
     *
     * @return
     */
    @Override
    public List<Project> initProject() {
        log.info("查询可用数据产品");
        Map<String, Project> tmpMap = new HashMap();

        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getStatus, 1);
        queryWrapper.isNotNull(Project::getVersion);
        List<Project> list = projectMapper.selectList(queryWrapper);
        for (Project item : list) {
            String key = getMapKey(item.getProductCode(), item.getEventType());
            tmpMap.put(key, item);
        }

        if (CollectionUtils.isEmpty(tmpMap)) {
            log.error("-----系统未加载到任何数据产品-----");
            return null;
        } else {
            log.info("----------查询可用数据产品tmp={}", JSON.toJSON(tmpMap.keySet()));
            map = tmpMap;
            return list;
        }
    }

    @Override
    public Project getProject(String projectCode, String eventCode) {
        return map.get(getMapKey(projectCode, eventCode));
    }


    private String getMapKey(String projectCode, String eventCode) {
        return projectCode + SysConstant.PROJECT_SPLIT + eventCode;
    }

    @Override
    public List<VariateVo> listByProductCodeAndEventType(String productCode, String eventType) {
        List<VariateVo> reList = new LinkedList<>();

        Map<String, Object> param = new HashMap<>();
        param.put("productCode", productCode);
        param.put("eventType", eventType);
        String url = coreRootUrl + "/productVariate/list";
        String result = null;
        try {
            result = HttpUtil.get(url, param);
            Result<List<JSONObject>> res = JSON.parseObject(result, new TypeReference<Result<List<JSONObject>>>() {
            });
            List<JSONObject> data = res.getData();
            if (!CollectionUtils.isEmpty(data)) {
                for (JSONObject obj : data) {
                    String fieldId = obj.getString("fieldId");
                    String fieldCn = obj.getString("fieldCn");
                    String intId = obj.getString("intId");
                    String status = obj.getString("status");
                    reList.add(new VariateVo(fieldId, fieldCn, intId, status));
                }
            }
        } catch (Exception e) {
            log.error("请求core服务异常,url={},param={},result={}", url, JSON.toJSONString(param), result, e);
        }
        return reList;
    }

    @Override
    public Page<Project> pageList(ProjectPageReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(req.getEventType())) {
            queryWrapper.eq(Project::getEventType, req.getEventType());
        }

        if (req.getStatus() != null) {
            queryWrapper.eq(Project::getStatus, req.getStatus());
        }

        if (StringUtils.isNotBlank(req.getName())) {
            queryWrapper.like(Project::getName, req.getName());
        }
        if (StringUtils.isNotBlank(req.getProductCode())) {
            queryWrapper.like(Project::getProductCode, req.getProductCode());
        }
        List<Project> list = projectMapper.selectList(queryWrapper);
        Page<Project> page = new Page<>(list, new PageInfo<>(list).getTotal(), req);
        return page;
    }

    @Override
    public Map<String, Project> mapByProjectIds(Collection<String> projectIds) {
        Map<String, Project> reMap = new HashMap<>();
        if (CollectionUtils.isEmpty(projectIds)) {
            return reMap;
        }

        List<Project> list = projectMapper.selectBatchIds(projectIds);
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(e -> reMap.put(e.getId() + "", e));
        }
        return reMap;
    }

    //激活版本为默认版本
    @Override
    public Integer activateProjectVersion(Long projectId, String version) {
        int re = 0;
        List<ProjectHist> list = projectConfService.listByProjectIdAndVersion(projectId,version,2);
        if (!CollectionUtils.isEmpty(list)) {
            Project record = new Project();
            record.setId(projectId);
            record.setVersion(version);
            re =  projectMapper.updateById(record);
        }
        return re;
    }
}
